<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of upload
 *
 * @author martin
 */
class upload{

        public function uploads($file) 
        {
            $this->swfUpload($file);                  
        }           
        
        
        
        /**
         *批量上传处理
         * @param type $file $_FILES
         */
        public function swfUpload($file)
        {
            
            $path = $this->setRoute('albums');
            $name = md5($file['tmp_name']).'.png';
            file_put_contents('image.txt','<img src="/'.$path.$name.'" />');
            if(move_uploaded_file($file['tmp_name'],$path.$name))                
                //保存数据库
                $this->createThumbs ($path,$name);
                $files = new Temp;
                $files->user = 'admin';
                $files->data = $path.$name;
                $files->attributes = $files;
                $files->save();                   
        }
        
        public function actionTemp()
        {
            $url= file_get_contents('image.txt');
            $url = str_replace('albums', 'thumbs', $url);
            echo $url;
        }
        
        /**
         *批量上传生成缩略图
         * @param type $path 主文件路径
         * @param type $name 主文件名称
         */
        private function createThumbs($path,$name)
        {
            $paths = $this->setRoute('thumbs');
            $thumb=Yii::app()->phpThumb->create($path.$name);
            $thumb->resize(100,100);
            if($thumb->save($paths.$name))
                return true;
            else 
                return false;
        }
        
        /**
         *生成目录路径
         * @param type $route 文件夹名称
         * @return string 主路径
         */
        private function setRoute($route)
        {
            $year=date('Y'); 
            $month=date('m'); 
            $folder = 'attachment/'.$route.'/';
            $path=$folder.$year.'/'.$month.'/'; 
            //如果目录不存在就创建目录 
            if(!file_exists($folder.$year.'/'))
            { 
                mkdir($folder.$year.'/','0777');                
            } 
            if(!file_exists($path))
            { 
                mkdir($path,'0777');                    
            }
            return $path;
        }
}

